<template>
    <div>
        <h2>水平垂直居中</h2>
        <div class="mode mode_1" :style="'background:'+ getRandomColor()">
            <p class="inside" :style="'background:'+ getRandomColor()">
                定位 + margin
            </p>
        </div>
        <div class="mode mode_2" :style="'background:'+ getRandomColor()">
            <p class="inside" :style="'background:'+ getRandomColor()">
                定位 + transform
            </p>
        </div>
        <div class="mode mode_3" :style="'background:'+ getRandomColor()">
            <p class="inside" :style="'background:'+ getRandomColor()">
                弹性盒子
            </p>
        </div>
        <div class="mode mode_4" :style="'background:'+ getRandomColor()">
            <p class="inside" :style="'background:'+ getRandomColor()">
                垂直实现不了 <br>
                line-height + inline-block
                
            </p>
        </div>
        <div class="mode mode_5" :style="'background:'+ getRandomColor()">
            <p class="inside" :style="'background:'+ getRandomColor()">
                grid
            </p>
        </div>
        <div class="mode mode_6" :style="'background:'+ getRandomColor()">
            <p class="inside" :style="'background:'+ getRandomColor()">
                不好用
            </p>
        </div>
    </div>
</template>

<script setup lang="ts">

function getRandomColor() {
    const letters = '0123456789ABCDEF'
    let color = '#'
    for (let i = 0; i < 6; i++) {
        color += letters[Math.floor(Math.random() * 16)];
    }
    return color;
}
</script>

<style lang="less" scoped>
.mode {
    width: 100vw;
    height: 100px;
    
    .inside {
        width: 50vw;
        height: 50px;
        border-radius: 5px;
        box-shadow: 0 0 10px rgb(0, 0, 0);
    }
}

.mode_1 {
    position: relative;
    
    .inside {
        position: absolute;
        left: 0;
        right: 0;
        top: 0;
        bottom: 0;
        margin: auto;
    }
}

.mode_2 {
    position: relative;
    
    .inside {
        position: absolute;
        left: 50%;
        top: 50%;
        transform: translate(-50%, -50%);
    }
}

.mode_3 {
    display: flex;
    align-items: center;
    justify-content: center;
}

.mode_4 {
    text-align: center;
    vertical-align: middle;
    line-height: 100px;
    .inside {
        display: inline-block;
        line-height: 1;
    }
}

.mode_5 {
    display: grid;
    place-items: center;
}

.mode_6 {
    display: table-cell;
    text-align: center; /* 水平居中 */
    vertical-align: middle; /* 垂直居中 */
    .inside{
        display: table-cell;
        margin: 0 auto;
    }
}

</style>